﻿using BankTransfer.Bank.Domain.Domain.Entity;
using BankTransfer.Bank.Domain.Repository;
using BankTransfer.Bank.Infrastructure.Repository.Builder;
using BankTransfer.Bank.Infrastructure.Repository.DAO;
using BankTransfer.Bank.Infrastructure.Repository.DO;
using BankTransfer.Bank.Types.Types;

namespace BankTransfer.Bank.Infrastructure.Repository.Impl
{
    public class AccountRepositoryImpl : IAccountRepository
    {
        private readonly AccountDAO accountDao;
        private readonly AccountBuilder accountBuilder;

        public AccountRepositoryImpl(AccountDAO accountDao, AccountBuilder accountBuilder)
        {
            this.accountDao = accountDao;
            this.accountBuilder = accountBuilder;
        }

        public Account Find(AccountId id)
        {
            AccountDO accountDO = accountDao.SelectById(id.Value);
            return accountBuilder.ToAccount(accountDO);
        }

        public Account Find(AccountNumber accountNumber)
        {
            AccountDO accountDO = accountDao.SelectByAccountNumber(accountNumber.Value);
            return accountBuilder.ToAccount(accountDO);
        }

        public Account Find(UserId userId)
        {
            AccountDO accountDO = accountDao.SelectByUserId(userId.Value);
            return accountBuilder.ToAccount(accountDO);
        }

        public Account Save(Account account)
        {
            AccountDO accountDO = accountBuilder.FromAccount(account);
            if (accountDO.Id > 0)
            {
                accountDao.Update(accountDO);
            }
            else
            {
                accountDao.Insert(accountDO);
            }
            return accountBuilder.ToAccount(accountDO);
        }
    }
}